import React, { useContext, useReducer } from 'react'
import GlobalContext from './store/context'
import reducer from './store/reducer'
import { NUMADD } from './store/actionType'
import { Button } from 'antd'

const Child1 = () => {
  //不需要consumer, useContext替代
  let { state, dispatch } = useContext(GlobalContext)
  return <div>
    子组件child1 -> {state.text} -> {state.num}
    <Button onClick={() => {
      dispatch({
        type: NUMADD,
        payload: 1
      })
    }}>Add</Button>
  </div>
}

const Child2 = () => {
  let { state
    // , dispatch
  } = useContext(GlobalContext)
  return <div>
    子组件child2 -> {state.text} -> {state.num}
  </div>
}

const RC = () => {
  // state ,dispatch
  // 可以在useReducer的第二个参数写初始状态;也可以在reducer.js写初始状态
  const [state, dispatch] = useReducer(reducer, {
    isShow: true,
    list: [],
    text: "我是公共的状态",
    num: 0
  }) // [公共的状态，改变公共状态的方法]

  return (
    // 自己封装context,并通过Provider往下提供状态和方法
    <GlobalContext.Provider value={{
      state,
      dispatch
    }}>
      <Child1 />
      <Child2 />
      父组件 -> {state.text} -> {state.num}
      <Button onClick={() => {
        dispatch({
          type: NUMADD,
          payload: -1
        })
      }}>Dec</Button>
    </GlobalContext.Provider>
  )
}

export default RC